<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="//cdn.jsdelivr.net/npm/phaser@3.60.0/dist/phaser.js"></script>
    <script src="../dist/iife/spine-phaser-v3.js"></script>
    <link rel="stylesheet" href="../../index.css" />
    <title>Spine Phaser Example</title>
  </head>

  <body class="p-4 flex flex-col items-center">
    <h1>Control bones</h1>
    <script>
      class ControlBonesExample extends Phaser.Scene {
        preload() {
          this.load.spineBinary(
            "stretchyman-data",
            "/assets/stretchyman-pro.skel"
          );
          this.load.spineAtlas(
            "stretchyman-atlas",
            "/assets/stretchyman-pma.atlas"
          );
        }

        create() {
          const stretchyman = this.add.spine(
            400,
            580,
            "stretchyman-data",
            "stretchyman-atlas"
          );
          stretchyman.animationState.setAnimation(0, "idle", true);
          stretchyman.updatePose(0);

          const controlBoneNames = [
            "back-arm-ik-target",
            "back-leg-ik-target",
            "front-arm-ik-target",
            "front-leg-ik-target",
          ];
          const controlBones = [];
          for (var i = 0; i < controlBoneNames.length; i++) {
            const bone = stretchyman.skeleton.findBone(controlBoneNames[i]);
            const point = { x: bone.worldX, y: bone.worldY };
            stretchyman.skeletonToPhaserWorldCoordinates(point);

            const control = this.add
              .circle(point.x, point.y, 4, 0xff00ff)
              .setData("bone", bone);
            controlBones.push(control);

            control.setInteractive();
            this.input.setDraggable(control);
            this.input.on(
              "drag",
              function (pointer, gameObject, dragX, dragY) {
                gameObject.x = dragX;
                gameObject.y = dragY;
              },
              this
            );
          }

          stretchyman.beforeUpdateWorldTransforms = () => {
            for (let controlBone of controlBones) {
              const bone = controlBone.getData("bone");
              const point = { x: controlBone.x, y: controlBone.y };
              stretchyman.phaserWorldCoordinatesToBone(point, bone);
              bone.x = point.x;
              bone.y = point.y;
            }
          };
        }
      }

      new Phaser.Game({
        type: Phaser.AUTO,
        width: 800,
        height: 600,
        type: Phaser.WEBGL,
        scene: [ControlBonesExample],
        plugins: {
          scene: [
            {
              key: "spine.SpinePlugin",
              plugin: spine.SpinePlugin,
              mapping: "spine",
            },
          ],
        },
      });
    </script>
  </body>
</html>
